<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑产品</title>
    <style>
        body { font-family: Arial, sans-serif; }
        .container { width: 300px; margin: 50px auto; }
        .form-group { margin-bottom: 10px; }
        label { display: block; margin-bottom: 5px; }
        input[type="text"], textarea { width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
        button { padding: 10px 20px; cursor: pointer; background-color: #28a745; color: white; border: none; border-radius: 4px; }
    </style>
</head>
<body>
<div class="container">
    <h2>编辑产品</h2>
    <form id="editProductForm">
        <div class="form-group">
            <label for="editProductName">产品名称:</label>
            <input type="text" id="editProductName" name="editProductName" required>
        </div>
        <div class="form-group">
            <label for="editProductDescription">产品描述:</label>
            <textarea id="editProductDescription" name="editProductDescription" required></textarea>
        </div>
        <div class="form-group">
            <label for="editProductPrice">价格:</label>
            <input type="number" id="editProductPrice" name="editProductPrice" required>
        </div>
        <div class="form-group">
            <label for="editProductImageURL">图片URL:</label>
            <input type="text" id="editProductImageURL" name="editProductimageurl" required>
        </div>
        <div class="form-group">
            <label for="editProductDetailURL">页面URL:</label>
            <input type="text" id="editProductDetailURL" name="editProductdetailurl" required>
        </div>
        <div class="form-group">
            <label for="editProductStockQuantity">产品库存:</label>
            <input type="number" id="editProductStockQuantity" name="editProductstock_quantity" required>
        </div>
        <div class="form-group">
            <button type="button" onclick="updateProduct()">更新产品</button>
            <button type="button" onclick="window.history.back()">取消</button>
        </div>
    </form>
</div>

<script>
    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
        var results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    function fetchProductDetails(productId) {
        fetch(`/api/products/${productId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                console.log('Product details:', data);
                document.getElementById('editProductName').value = data.name.replace(/\r\n/g, ''); // 移除换行符
                document.getElementById('editProductDescription').value = data.description;
                document.getElementById('editProductPrice').value = data.price.toString();
                document.getElementById('editProductImageURL').value = data.imageURL.replace(/&quot;/g, ''); // 替换 HTML 实体编码
                document.getElementById('editProductDetailURL').value = data.detailUrl.replace(/&quot;/g, ''); // 替换 HTML 实体编码
                document.getElementById('editProductStockQuantity').value = data.stockQuantity.toString();
                document.getElementById('editProductName').dataset.productId = data.productID;
            })
            .catch(error => {
                console.error('Error fetching product details:', error);
                alert('获取产品详情失败: ' + error.message);
            });
    }

    function updateProduct() {
        const name = document.getElementById('editProductName').value;
        const description = document.getElementById('editProductDescription').value;
        const price = document.getElementById('editProductPrice').value;
        const productId = document.getElementById('editProductName').dataset.productId;
        const stockQuantity = document.getElementById('editProductStockQuantity').value;
        const detailUrl = document.getElementById('editProductDetailURL').value;
        const imageURL = document.getElementById('editProductImageURL').value;

        fetch(`/api/products/${productId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                name,
                description,
                price,
                stockQuantity,
                detailUrl,
                imageURL
            }),
        })
            .then(response => response.json())
            .then(data => {
                console.log('Success:', data);
                alert('产品更新成功');
                window.history.back();
            })
            .catch(error => {
                console.error('Error:', error);
                alert('产品更新失败: ' + error.message);
            });
    }

    document.addEventListener('DOMContentLoaded', function() {
        const productId = getParameterByName('id');
        if (productId) {
            fetchProductDetails(productId);
        }
    });
</script>
</body>
</html>